# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# date: 2/7/12 6:26 PM
# Filename: resp_time.py

#
# Copyright 2011 Youku
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import ConfigParser
import datetime
import time
from constants import RESP_CODE
from handlers.handler import BaseHandler
from util import log

### read configurations from conf/stat.cfg ###
_config = ConfigParser.RawConfigParser()
_config.read('../conf/stat.cfg')

_section = 'DataFile'
_path = _config.get(_section, 'path')
_filename = _config.get(_section, 'filename')
_timeformat = _config.get(_section, 'timeformat')

### global variables ###
_log = log.getLogger()
_enable = _config.get(_section, 'enable')
_now = datetime.datetime.now()
_data_file_path = _path + _filename.format(time.strftime(_timeformat))

class RespTimeHandler(BaseHandler):
    '''
    接口访问时长统计数据的收集

    page	页面名称(需要经过URL UTF-8编码)	 Not NULL
    api	 接口URI	 Not NULL
    resptime	 响应时间(ms)
    '''

    def get(self, *args, **kwargs):
        _log.info('class:RespTimeHandler method:get()')

        if self._finished:
            return None

        # step 1 : get all arguments:
        page = self.get_argument('page', None)
        api = self.get_argument('api', None)
        resptime = self.get_argument('resptime', None)

        # step 2 : verigy all arguments:
        if not page:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_page)
        elif not api:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_api)
        elif not resptime:
            self.writeAndFinish(RESP_CODE.resp_code_invalid_resptime)

        if self._finished:
            return None

        # step 3 : record the argument to local util file , according to the LogSpecification
        if _enable:
            # TODO implement
            pass
        self.writeAndFinish(RESP_CODE.resp_code_success)

handlers = [(ur'/stat/4', RespTimeHandler)]